package com.newtouch.cq.security.config.handle;

import cn.hutool.json.JSONUtil;
import com.newtouch.cq.lang.em.BaseExceptionEnum;
import com.newtouch.cq.lang.result.MccResult;
import com.newtouch.cq.security.exception.AuthException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Alex
 * @Description 自定义异常处理类
 * @time 2021/8/20 17:06
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        MccResult result = MccResult.failureBmc(BaseExceptionEnum.ERROR);
        if (e instanceof AuthException) {
            result.setCode(((AuthException) e).getCode());
            result.setMessage(e.getMessage());
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
